from app import db
from datetime import datetime

class Brand(db.Model):
    __tablename__ = 'brands'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True, nullable=False)
    logo = db.Column(db.String(255))
    description = db.Column(db.Text)
    country = db.Column(db.String(50))
    founded_year = db.Column(db.Integer)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联车辆
    cars = db.relationship('Car', backref='brand', lazy=True)
    
    def __init__(self, name, **kwargs):
        self.name = name
        self.logo = kwargs.get('logo')
        self.description = kwargs.get('description')
        self.country = kwargs.get('country')
        self.founded_year = kwargs.get('founded_year')
    
    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'logo': self.logo,
            'description': self.description,
            'country': self.country,
            'founded_year': self.founded_year,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }